class Solution(object):
    def maxValueAfterReverse(self, nums):
        n = len(nums)
        p1 = [0] * n
        p2 = [0] * n
        for i in range(1, n):
            p1[i] = abs(nums[i] - nums[i - 1])
            p2[i - 1] = abs(nums[i - 1] - nums[i])
        ans = sum(p1)
        s10 = [0] * n
        s11 = [0] * n
        s12 = [0] * n
        s13 = [0] * n
        s20 = [0] * n
        s21 = [0] * n
        s22 = [0] * n
        s23 = [0] * n
        for i in range(1, n):
            if i == 1:
                s10[i] = nums[i] + nums[i - 1] - p1[i]
                s11[i] = nums[i] - nums[i - 1] - p1[i]
                s12[i] = - nums[i] + nums[i - 1] - p1[i]
                s13[i] = - nums[i] - nums[i - 1] - p1[i]
            else:
                s10[i] = max(s10[i - 1], nums[i] + nums[i - 1] - p1[i])
                s11[i] = max(s11[i - 1], nums[i] - nums[i - 1] - p1[i])
                s12[i] = max(s12[i - 1], - nums[i] + nums[i - 1] - p1[i])
                s13[i] = max(s13[i - 1], - nums[i] - nums[i - 1] - p1[i])
        for i in range(n - 2, -1, -1):
            if i == n - 2:
                s20[i] = nums[i] + nums[i + 1] + p2[i]
                s21[i] = nums[i] - nums[i + 1] + p2[i]
                s22[i] = - nums[i] + nums[i + 1] + p2[i]
                s23[i] = - nums[i] - nums[i + 1] + p2[i]
            else:
                s20[i] = min(s20[i + 1], nums[i] + nums[i + 1] + p2[i])
                s21[i] = min(s21[i + 1], nums[i] - nums[i + 1] + p2[i])
                s22[i] = min(s22[i + 1], - nums[i] + nums[i + 1] + p2[i])
                s23[i] = min(s23[i + 1], - nums[i] - nums[i + 1] + p2[i])
        diff = 0
        for i in range(1, n - 2):
            diff = max(diff, s10[i] - s20[i + 1], s11[i] - s21[i + 1], s12[i] - s22[i + 1], s13[i] - s23[i + 1])
        for j in range(1, n - 1):
            diff = max(diff, abs(nums[j - 1] - nums[-1]) - abs(nums[j - 1] - nums[j]))
            diff = max(diff, abs(nums[j + 1] - nums[0]) - abs(nums[j + 1] - nums[j]))
        return ans + diff

data = Solution()
nums = [2, 3, 1, 5, 4]
print(data.maxValueAfterReverse(nums))
